package com.app.xinfadi.ui.purchase_plan.center_purchase_plan.new_bill_of_sales_status;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.app.xinfadi.R;
import com.app.xinfadi.base.BaseActivity;
import com.app.xinfadi.base.BaseFragment;
import com.app.xinfadi.dao.HomeDao;
import com.app.xinfadi.ui.MainActivity;
import com.app.xinfadi.ui.home.view.GridViewImageAdapter;
import com.app.xinfadi.ui.home.view.GridViewImageNoAddAdapter;
import com.app.xinfadi.ui.purchase_plan.center_purchase_plan.NewBillOfSalesBtnActivity;
import com.app.xinfadi.util.LogUtil;
import com.app.xinfadi.util.Toast;
import com.app.xinfadi.widget.MyGridView;
import com.app.xinfadi.widget.gson.Success;
import com.app.xinfadi.widget.image_browser.ImageBrowserActivity;
import com.google.gson.Gson;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * function: 出货登记单——部分完成
 * Created by Wutengfei on 2016/1/25.
 */
public class NewBillOfSalesPartFinishFragment extends BaseFragment {

    private static final java.lang.String TAG = NewBillOfSalesFinishFragment.class.getSimpleName();
    private View view;
    private Button submitBtn;
    private List<String> selectedImageUrls;
    private MyGridView photoGridView;
    private TextView uploadImgTv;
    private boolean isUploading = false;
    private View upload_imgLinLay;
    private String currentStatus = "04";
    private String plan_id;
    private ArrayList<File> imageFiles;
    private EditText resultEdt;
    private EditText NumberEdt;

    public static NewBillOfSalesPartFinishFragment getInstance(String plan_id) {
        NewBillOfSalesPartFinishFragment instance = new NewBillOfSalesPartFinishFragment();
        Bundle args = new Bundle();
        args.putString("plan_id", plan_id);
        instance.setArguments(args);
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.new_bill_of_sales_part_finish_layout_fragment, null);
        plan_id = (String) getArguments().get("plan_id");
        initView();
        initData();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return view;
    }


    private void initView() {
        submitBtn = (Button) view.findViewById(R.id.submitBtn);
        submitBtn.setOnClickListener(this);
        uploadImgTv = (TextView) view.findViewById(R.id.uploadImgTv);
        uploadImgTv.setOnClickListener(this);
        upload_imgLinLay = view.findViewById(R.id.upload_imgLinLay);
        upload_imgLinLay.setOnClickListener(this);
        NumberEdt = (EditText) view.findViewById(R.id.NumberEdt);
        resultEdt = (EditText) view.findViewById(R.id.resultEdt);
        initPhotographView();
    }

    private void initData() {

    }

    private void uplodeImage() {
        List<String> image = new ArrayList<String>();
        imageFiles = new ArrayList<File>();
        for (String imageStr : selectedImageUrls) {
            String imageUrl = imageStr.replace("file://", "");
            LogUtil.e(TAG, "PHOTOGRAPH_url:" + imageUrl + " directory" + Environment.getExternalStorageDirectory().getPath());
            File imageFile = new File(imageUrl);
            imageFiles.add(imageFile);
            image.add(imageFiles.size() - 1 + "");
        }
        int imageFileSize = imageFiles.size();
        if (imageFileSize > 0)
            imageFiles.remove(imageFileSize - 1);
        File[] imageFiles1 = imageFiles.toArray(new File[imageFiles.size()]);
        HomeDao homeDao = new HomeDao();
        try {
            homeDao.finishPlans(imageFiles1, plan_id, resultEdt.getText().toString().trim(), currentStatus, NumberEdt.getText().toString().trim(), new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    Toast.makeText(context, "登出记录失败！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    Success success = new Gson().fromJson(responseString, Success.class);
                    if(success.success){
                        Toast.makeText(context, "登出记录成功！", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "登出记录失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化 拍照View
     */
    private void initPhotographView() {
        selectedImageUrls = new ArrayList<String>();
        photoGridView = (MyGridView) view.findViewById(R.id.photoGridView);
        initPhotographGridData();

    }

    /**
     * 获取图片选择URL列表 PhotographUrlList
     */
    public void onEventMainThread(ArrayList<String> imageUrl) {
        LogUtil.e(TAG, "onEventMainThread(ArrayList<String> imageUrl)");
        int length = selectedImageUrls.size();

        if (isUploading && imageUrl != null && imageUrl.size() > 0) {
            upload_imgLinLay.setVisibility(View.GONE);
            if (length > 0) {
                selectedImageUrls.remove(length - 1);
                selectedImageUrls.addAll(imageUrl);
            } else {
                selectedImageUrls.addAll(imageUrl);
            }
            initPhotographGridData();
        } else {
            upload_imgLinLay.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化 拍照界面的 image gridView 数据
     */
    private void initPhotographGridData() {
        int length1 = selectedImageUrls.size();
        if (length1 > 0) {
            photoGridView.setVisibility(View.VISIBLE);
            // 最后一个 添加图片按钮
            selectedImageUrls.add("add");
            GridViewImageAdapter gridViewImageNoAddAdapter = new GridViewImageAdapter(context, selectedImageUrls);
            photoGridView.setAdapter(gridViewImageNoAddAdapter);
            gridViewImageNoAddAdapter.setAddImageClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intentToImageBrowserActivity(ImageBrowserActivity.IMAGE_EXPORE);
                }
            });
//            savePhotographData(false);
//            } else {
//                GridViewImageNoAddAdapter gridViewImageNoAddAdapter = new GridViewImageNoAddAdapter(context, selectedImageUrls);
//                photoGridView.setAdapter(gridViewImageNoAddAdapter);
//            }

        } else {
            photoGridView.setVisibility(View.GONE);
        }
    }

    /**
     * @param browser_type ImageBrowserActivity.IMAGE_EXPORE 相册
     *                     ImageBrowserActivity.ESCORT_REPORT_EXPORE 陪护报告图片
     */
    private void intentToImageBrowserActivity(int browser_type) {
        Intent intent = new Intent(context, ImageBrowserActivity.class);
        intent.putExtra("selected_size", selectedImageUrls.size() - 1 > 0 ? selectedImageUrls.size() - 1 : 0);
        intent.putExtra("browser_type", browser_type);
        ((BaseActivity) context).startActivityForResult(intent, 10);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.submitBtn:
                uplodeImage();
                ((NewBillOfSalesBtnActivity) context).popAllActivityExceptOne(MainActivity.class);
                break;
            case R.id.uploadImgTv:
                isUploading = true;
                intentToImageBrowserActivity(ImageBrowserActivity.IMAGE_EXPORE);
                break;
            case R.id.upload_imgLinLay:
                isUploading = true;
                intentToImageBrowserActivity(ImageBrowserActivity.IMAGE_EXPORE);

        }
    }

    @Override
    public void onResume() {
        LogUtil.e(TAG, "onResume");
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.e(TAG, "onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.e(TAG, "onDestroy");
        EventBus.getDefault().unregister(this);

    }

    public void setIsUploading(boolean isUploading) {
        this.isUploading = isUploading;
    }
}
